package com.example.administrator.base.activity;


import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.erebus.blelocklibrary.config.Config;
import com.erebus.blelocklibrary.config.LockType;
import com.erebus.blelocklibrary.impl.AndroidBle;
import com.erebus.blelocklibrary.inter.IBLE;
import com.erebus.blelocklibrary.inter.OnConnectionListener;
import com.erebus.blelocklibrary.inter.OnDeviceSearchListener;
import com.erebus.blelocklibrary.utils.GlobalParameterUtils;
import com.example.administrator.base.R;
import com.example.administrator.base.baseActivity.BaseActivity;
import com.example.administrator.base.bean.OpenLockBlue;
import com.example.administrator.base.bean.ReLogout;
import com.example.administrator.base.util.GsonTools;
import com.example.administrator.base.util.SharedPreferencesUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ChangeCityBlue extends BaseActivity {
    @InjectView(R.id.Toolbar)
    android.support.v7.widget.Toolbar Toolbar;
    @InjectView(R.id.ib_bluetooth)
    ImageView ibBluetooth;
    @InjectView(R.id.lv_bluetooth)
    ListView lvBluetooth;
    private IBLE ible;
    SweetAlertDialog sweetAlertDialog;
    SimpleAdapter adapter;
    List<Map<String, Object>> datalist;
    Map<String, Object> map;
    BroadcastReceiver broadcastReceiver;
    private int bleStatus;
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_city_blue);
        ButterKnife.inject(this);
        bleStatus=0;
        Toolbar.setTitle("赳猎人");
        Toolbar.setSubtitle("车辆解绑城市");
        setSupportActionBar(Toolbar);
        Toolbar.setNavigationIcon(R.drawable.backbar);
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        sweetAlertDialog = new SweetAlertDialog(this, 5);
        sweetAlertDialog.setCanceledOnTouchOutside(false);
        sweetAlertDialog.setTitleText("搜索中....");
        datalist = new ArrayList<>();
        ible = new AndroidBle(this);
        if (!ible.isEnable()) {
            showToast("请打开蓝牙");
            ible.enableBluetooth();
        }
        adapter = new SimpleAdapter(this, datalist, R.layout.orderlistitem,
                new String[]{"name", "number", "img", "time"},
                new int[]{R.id.tv_pointName, R.id.tv_number, R.id.im_stage, R.id.tv_timex});
        lvBluetooth.setAdapter(adapter);
        lvBluetooth.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final String  name = String.valueOf(datalist.get(position).get("name"));
                sweetAlertDialog = new SweetAlertDialog(ChangeCityBlue.this, SweetAlertDialog.WARNING_TYPE);
                sweetAlertDialog.setCanceledOnTouchOutside(true);
                sweetAlertDialog
                        .setTitleText("验证车锁")
                        .setContentText("请仔细核对锁名，蓝牙地址，信号强度等信息。若无法确定该地址与锁对应，可点击验证按钮。")
                        .setConfirmText("验证车锁")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                sDialog.changeAlertType(SweetAlertDialog.PROGRESS_TYPE);
                                sDialog.setContentText("正在验证开锁，请稍等");
                                sDialog.setTitleText("开锁验证");
                                getCarNumber(name,sDialog);
                            }
                        })
                        .show();

            }
        });
    }

    @OnClick(R.id.ib_bluetooth)
    public void onViewClicked() {
        sweetAlertDialog.show();
        ible.startScan(new OnDeviceSearchListener() {
            @Override
            public void onScanDevice(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
                if (bluetoothDevice == null || TextUtils.isEmpty(bluetoothDevice.getAddress())) {
                    return;
                }
                String address = bluetoothDevice.getAddress();
                String name = bluetoothDevice.getName();
                if (-80<=i&&i<0){
                    map = new HashMap<>();
                    map.put("time", name);
                    map.put("name", address);
                    map.put("number",i);
                    map.put("img",R.drawable.uploadunband);
                    datalist.add(map);
                }
            }
        });
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!isFinishing() && ible.isEnable()) {
                    Log.i("34545454", "stop");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ible.stopScan();
                            if (datalist != null) {
                            Collections.sort(datalist, new Comparator<Map<String, Object>>() {
                                @Override
                                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                                    if ((Integer) o1.get("number") > (Integer) o2.get("number")) {
                                        return -1;
                                    } else if ((Integer) o1.get("number") < (Integer) o2.get("number")) {
                                        return 1;
                                    } else {
                                        return 0;
                                    }
                                }
                            });
                        }else {
                                showToast("周边未发现蓝牙设备");
                            }
                            adapter.notifyDataSetChanged();
                            sweetAlertDialog.dismiss();
                        }
                    });
                }
            }
        }, 6000);
    }

    @Override
    protected void onDestroy() {
        ible.disconnect();
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
            broadcastReceiver = null;
        }
        super.onDestroy();
    }

    @Override
    protected void onResponseSuccess(Response response, String action) {

    }

    @Override
    protected void onResponseFailure(Throwable e, String action) {

    }


    /*蓝牙车辆解除绑定*/
    public void undengjicarblue(final SweetAlertDialog sweetAlertDialog, String mac) {
        String location = String.valueOf(SharedPreferencesUtils.getParam(ChangeCityBlue.this, "changelocklocation", ""));
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "CANCELLATIONCITYNOBYMAC")
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(ChangeCityBlue.this, "adminId", "")))
                .add("mac", mac)
                .add("address", location)
                .build();
        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/administrator?")
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        final ReLogout mse = GsonTools.changeGsonToBean(string, ReLogout.class);
                        Log.i("121555121", "" + string);
                        if (mse != null) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    sweetAlertDialog.dismiss();
                                    Toast.makeText(ChangeCityBlue.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();

                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    sweetAlertDialog.dismiss();
                                    Toast.makeText(ChangeCityBlue.this, "数据异常请重试", Toast.LENGTH_LONG).show();

                                }
                            });
                        }

                    } else {
                        throw new IOException("Unexpected code " + response);
                    }
                } catch (IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sweetAlertDialog.dismiss();
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();


    }

    /*获取车号等信息*/
    public void getCarNumber(final String mac, final SweetAlertDialog sweetAlertDialog) {
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "GETBIKEINFOBYMAC")
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(ChangeCityBlue.this, "adminId", "")))
                .add("mac", mac)
                .build();
        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/administrator?")
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        final String string = response.body().string();
                        Log.i("121555121", "" + string);
                        final OpenLockBlue mse = GsonTools.changeGsonToBean(string, OpenLockBlue.class);
                        if (mse != null) {
                            if (mse.getCode()==1){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {

                                broadcastReceiver = new BroadcastReceiver() {
                                    @Override
                                    public void onReceive(Context context, Intent intent) {
                                        String action = intent.getAction();
                                        String data = intent.getStringExtra("data");
                                        switch (action) {
                                            case Config.TOKEN_ACTION:
                                                Log.d(TAG, "get token");
                                                new Handler().postDelayed(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        ible.openLock();
                                                    }
                                                }, 1000);
                                                break;
                                            case Config.OPEN_ACTION:
                                                if (TextUtils.isEmpty(data)) {
                                                    Log.d(TAG, "开锁失败");
                                                   showToast("开锁失败");
                                                    sweetAlertDialog.dismiss();
                                                } else {
                                                    Log.d(TAG, "开锁成功");
                                                   showToast("开锁成功");
                                                    sweetAlertDialog.changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                                                    sweetAlertDialog.setTitleText("开锁成功");
                                                    sweetAlertDialog.setContentText("锁已打开，请确认该锁即为需要解除绑定的锁。");
                                                    sweetAlertDialog.setConfirmText("确认解绑");
                                                    sweetAlertDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                                        @Override
                                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                                            sweetAlertDialog.setTitleText("").setContentText("正在解绑...").changeAlertType(SweetAlertDialog.PROGRESS_TYPE);
                                                            undengjicarblue(sweetAlertDialog,mac);
                                                        }
                                                    });
                                                }
                                                break;
                                        }
                                    }
                                };

                                registerReceiver(broadcastReceiver, Config.initFilter());
                                GlobalParameterUtils.getInstance().setLockType(LockType.MTS);
                                Config.key = getKey(mse.getBikeInfo().getNewKey());
                                Config.password = getPassword(mse.getBikeInfo().getNewPassword());
                                        ible.startScan(new OnDeviceSearchListener() {
                                            @Override
                                            public void onScanDevice(final BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
                                                if (bluetoothDevice == null || TextUtils.isEmpty(bluetoothDevice.getAddress()))
                                                    return;
                                                String bluetoothMac = bluetoothDevice.getAddress();
                                                if (mac.equalsIgnoreCase(bluetoothMac)) {
                                                    Log.d("3378451844154", "finded");
                                                    bleStatus = 0;
                                                    ible.stopScan();
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            ible.connectDevice(bluetoothDevice, new OnConnectionListener() {
                                                                @Override
                                                                public void onConnect() {
                                                                    Log.d("3378451844154", "onConnect");
                                                                }

                                                                @Override
                                                                public void onDisconnect(int state) {
                                                                    Log.d("3378451844154", "连接失败");
                                                                    if (!isFinishing()) {
                                                                        Log.d("3378451844154", "连接失败1");
                                                                        Log.i("3378451844154", "" + isFinishing());
                                                                       showToast("连接失败");
                                                                        sweetAlertDialog.dismiss();
                                                                    }
                                                                }

                                                                @Override
                                                                public void onServicesDiscovered(String name, String address) {
                                                                    getToken();
                                                                }
                                                            });
                                                        }
                                                    });
                                                }
                                            }
                                        });
                                        bleStatus = 1;
                                        new Handler().postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                if (!isFinishing() && ible.isEnable()&& bleStatus == 1) {
                                                    ible.stopScan();
                                                   showToast("连接超时");
                                                    sweetAlertDialog.dismiss();
                                                }
                                            }
                                        }, 15 * 1000);
                                    }
                                });
                            }
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    sweetAlertDialog.dismiss();
                                    Toast.makeText(ChangeCityBlue.this, "数据异常请重试", Toast.LENGTH_LONG).show();

                                }
                            });
                        }

                    } else {
                        throw new IOException("Unexpected code " + response);
                    }
                } catch (IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sweetAlertDialog.dismiss();
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();


    }
    private byte[] getPassword(String passWord) {
        byte[] buf = new byte[passWord.length() / 2];
        for (int i = 0; i < buf.length; i++) {
            buf[i] = (byte) Integer.parseInt(passWord.substring(i * 2, i * 2 + 2));
        }
        return buf;
    }

    private byte[] getKey(String key) {
        byte[] buf = new byte[key.length() / 2];
        for (int i = 0; i < key.length() / 2; i++) {
            buf[i] = (byte) Integer.parseInt(key.substring(i * 2, i * 2 + 2));
        }
        return buf;
    }

    private void getToken() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                ible.getToken();
                Log.i("3378451844154", "" + ible.getToken());
            }
        }, 1500);
    }

}
